<template>
  <div>
    <ul>
      <li>姓名：<input type="text" v-model="obj.uname" /></li>
      <li>年龄：<input type="number" value="0" v-model="obj.age" /></li>
      <li>
        性别：<select v-model="obj.sex">
          <option value="男">男</option>
          <option value="女">女</option>
        </select>
      </li>
      <li><input type="button" value="添加/修改" @click="add" /></li>
    </ul>
    <table>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>性别</th>
          <th>年龄</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
    <span>年龄总和？？？{{ ages }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        {
          uname: "李姥爷",
          age: "20",
          sex: "男",
        },
        {
          uname: "李哥哥",
          age: "18.5",
          sex: "男",
        },
        {
          uname: "李弟弟",
          age: "18",
          sex: "男",
        },
      ],
      obj: {
        uname: "",
        age: "",
        sex: "",
      },
      inx: "",
    };
  },
  methods: {
    add() {
      if (!this.obj.uname) return alert("请输入姓名");
      if (!this.obj.age) return alert("请输入年龄");
      if (!this.obj.sex) return alert("请选择性别");

      // 有索引就是修改 无索引就是添加
      if (this.inx !== "") {
        // console.log(this.inx);
        this.arr[this.inx].uname = this.obj.uname;
        this.arr[this.inx].age = this.obj.age;
        this.arr[this.inx].sex = this.obj.sex;
        this.inx = "";
      } else {
        this.arr.push({
          uname: this.obj.uname,
          age: this.obj.age,
          sex: this.obj.sex,
        });
      }
      this.obj.uname = "";
      this.obj.age = "";
      this.obj.sex = "";
    },
    del(index) {
      // console.log(index);
      return this.arr.splice(index, 1);
    },
    edit(index) {
      // console.log(index);
      this.obj.uname = this.arr[index].uname;
      this.obj.age = this.arr[index].age;
      this.obj.sex = this.arr[index].sex;
      this.inx = index;
    },
  },
  computed: {
    ages() {
      var sum = 0;
      this.arr.forEach((item) => {
        sum += item.age - 0;
        // -0 隐式转换为数字型
      });
      return sum;
    },
  },
};
</script>
<style scoped>
li {
  list-style: none;
}
table {
  width: 400px;
  line-height: 30px;
  text-align: center;
  border-collapse: collapse;
}
td,
th {
  border: 1px solid #000;
}
button {
  margin-right: 5px;
}
</style>
